#!/usr/evn/bin python
#coding:utf-8

import re
import os
import sys
import types
import inspect
import operator
import pprint
from optparse import OptionParser

SLICE_SRC = os.path.abspath(os.path.join("slice"))
sys.path.append(SLICE_SRC)

slice_module = __import__("urls", {}, {})
app = getattr(slice_module, "slicehandle")

def main(*args, **kw):
    n = kw.get('n')
    c = kw.get('c')
    u = kw.get('u')
    t = kw.get('t', '').strip()
    #print n, c, u, args

    urls = list(args)
    if u:
        for i in open(u):
            if i and t + i not in urls:
                urls.append(t + i.strip())
    urls = filter(lambda x: len(x) > 0, urls)
    closted = cluster(urls)
    #pprint.pprint(closted.items())
    print "Init Date:"
    urls = []
    for k, v in closted.iteritems():
        urls.extend(set(v[:2]))
    #urls = reduce(lambda x, y: list(x) + list(y[1][:5]), [] + closted.items())
    #pprint.pprint(urls)
    stic = {}
    ilen_max = 0
    plen_max = 0
    tlen_max = 0
    for i in urls:
        #print i
        ret = os.popen('ab -n %d -c %d %s' % (n, c, i)).read()
        pers = re.search("Requests per second:\W+(\d+\.\d+)", ret)
        pers = pers.group(1) if pers else pers
        
        tpr = re.search("Time per request:\W+(\d+\.\d+) \[ms\] \(mean\)", ret)
        tpr = tpr.group(1) if tpr else tpr

        ilen_max = max(ilen_max, len(i))
        plen_max = max(plen_max, len(str(pers)))
        tlen_max = max(tlen_max, len(str(tpr)))
        stic[i] = (pers, tpr)

    ls = list(stic.iteritems())
    sorted(ls, key=operator.itemgetter(0))
    
    pTitle = "Req Per Sec"
    tTitle = "Time per Req"
    plen_max = max(plen_max, len(pTitle))
    tlen_max = max(tlen_max, len(tTitle))
    print "%s %s %s" % ("URL:".ljust(ilen_max), pTitle.rjust(plen_max), tTitle.rjust(tlen_max))
    for url, (pers, tpr) in ls:
        print "%s %s %s" % (url.ljust(ilen_max), str(pers).rjust(plen_max), str(tpr).rjust(tlen_max))

def generation_urls():
    raise NotImplemented("Sorry, I haven't time")

def cluster(ls):
    ret = {}
    for i in ls:
        ped = re.sub("/([a-zA-Z0-9\-]{6})/", "//", i)
        ped = re.sub("/\d+/", "//", ped)
        ped = re.sub("/[^/]*%252F[^/]*/", "//", ped)
        
        if not ret.get(ped):
            ret[ped] = []

        ret[ped].append(i)

    return ret
        
if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option('-n','--number',
            dest='n',
            type='int',
            default=100,
            help='number of request')
    parser.add_option('-c','--concurrency',
            dest='c',
            type='int',
            default=1, 
            help='Number of multiple requests to make')
    parser.add_option('-u', '--urls',
            dest='u',
            help='file of urls')
    parser.add_option('-g', '--generation-url',
            dest='g',
            action='store_true',
            help='generation urls file from slice/settings.py')
    parser.add_option('-t', '--target-host',
            dest='t',
            help='generation urls for they hostname')
    options, args = parser.parse_args()
    
    if options.g:
        generation_urls()
    else:
        main(*args, **dict([(k, getattr(options, k)) for k in dir(options)]))
